# _*_ coding:utf-8 _*_
# @Time  : 2023.04.07
# @Author: zizlee
from fastapi import APIRouter, Header, Query, Body
from pydantic import BaseModel, validator, conint
from hutool import security
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils
from db import FAConnection

from . import handler_utils

quota_coin_api = APIRouter()


# 查询用户的瑞币明细
@quota_coin_api.get('/my/')
def query_user_quota(ruizy_token: str = Header(...), page: int = Query(1), page_size: int = Query(30)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    # 直接查询
    with FAConnection() as cursor:

        cursor.execute('SELECT SQL_CALC_FOUND_ROWS * FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT %s,%s;',
                       (person['uid'], (page - 1) * page_size, page_size))
        quota_list = list(cursor.fetchall())
        cursor.execute('SELECT FOUND_ROWS() AS total;')
        total_obj = cursor.fetchone()
        total_count = total_obj['total'] if total_obj else 0  # 当前总数
        if page > 1:
            cursor.execute('SELECT id,user_id,quota_remain FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT 1;',
                           [person['uid']])
            _quota = cursor.fetchone()
            current = _quota['quota_remain'] if _quota else 0
        else:
            current = quota_list[0]['quota_remain'] if quota_list else 0
    for row in quota_list:
        row['create_time'] = row['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        row['module_name'] = handler_utils.get_module_name(row['module_name'])
    return AllResponse.operate_successfully(data={
        'quota': quota_list,
        'total_count': total_count,
        'current_quota': current
    })


# 管理查询用户的最新情况
@quota_coin_api.get('/last/')
def query_quota_last(ruizy_token: str = Header(...), uid: int = Query(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    with FAConnection() as cursor:
        cursor.execute("SELECT * FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT 1;", [uid])
        quota = cursor.fetchone()
    data = {
        'last_quota': 0,
        'last_time': '',
        'last_desc': '',
    }
    if quota:
        data['last_quota'] = quota['quota_remain']
        data['last_time'] = datetime_utils.to_string(quota['create_time'], is_time=True)
        data['last_desc'] = quota['description']
    return AllResponse.operate_successfully(data=data)


class ChangeQuota(BaseModel):
    new_quota: int
    action: str
    uid: conint(ge=1)

    @validator('action')
    def validate_action(cls, value):
        if value not in ['add', 'reset', 'reduce']:
            raise ValueError('操作错误')
        return value


# 增加一个记录
@quota_coin_api.post('/change/')
def change_quota(ruizy_token: str = Header(...), change: ChangeQuota = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    if not security.operator_is_manager(person):
        return AllResponse.forbidden_error()
    sql = """
        INSERT INTO ruizy_user_quota (user_id,module_name,module_id,description,quota_change,quota_remain)
        VALUES (%s,%s,%s,%s,%s,%s);
    """
    desc = {
        'add': '系统增加额度',
        'reset': '系统重置额度',
        'reduce': '系统减少额度'
    }
    quota_change = -change.new_quota if change.action == 'reduce' else change.new_quota
    quota_remain = quota_change
    with FAConnection() as cursor:
        if change.action != 'reset':
            cursor.execute("SELECT * FROM ruizy_user_quota WHERE user_id=%s ORDER BY create_time DESC LIMIT 1;", [change.uid])
            quota = cursor.fetchone()
            if quota:
                quota_remain = quota['quota_remain'] + quota_change
        cursor.execute(sql, [change.uid, change.action, 0, desc.get(change.action), quota_change, quota_remain])
    return AllResponse.operate_successfully()
